﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Beeflys
{
    public abstract partial class AActor
    {
        private readonly Dictionary<Type, AComponent> components = new Dictionary<Type, AComponent>();
        
        public Task<IEnumerable<AComponent>> GetComponentsAsync()
        {
            return Task.FromResult<IEnumerable<AComponent>>(this.components.Values);
        }

        public async Task<TComponent> AddComponentAsync<TComponent>() where TComponent : AComponent, new()
        {
            var type = typeof(TComponent);
            if(this.components.ContainsKey(type))
            {
                return null;
            }

            var component = new TComponent();
            component.Constructor(this);
            var awaker = component as IAwake;
            if (awaker != null)
            {
                await awaker.OnAwakeAsync();
            }

            this.components.Add(type, component);
            return component;
        }
        
        public async Task<bool> DestroyComponentAsync(AComponent component)
        {
            var type = component.GetType();
            if (!this.components.ContainsKey(type))
            {
                return false;
            }
            
            if (component is IDestroy destroyer)
            {
                await destroyer.OnDestroyAsync();
            }
            component.Destructor();
            this.components.Remove(type);
            return true;
        }

        public Task<TComponent> GetComponentAsync<TComponent>() where TComponent : AComponent, new()
        {
            var type = typeof(TComponent);
            if(this.components.ContainsKey(type))
            {
                var component = this.components[type] as TComponent;

                return Task.FromResult(component);
            }

            return Task.FromResult<TComponent>(null);
        }

        private async Task ComponentsInternalDestroyAsync()
        {
            foreach (var item in this.components)
            {
                await this.DestroyComponentAsync(item.Value);
            }

            this.components.Clear();
        }
    }
}